import { exec } from "child_process";

export async function systemExec(cmd: string, option?: any) {
    return new Promise((resolve, reject) => {
        var t = Date.now();
        console.log("开始执行:" + cmd);
        exec(cmd, option, (err, stdout, stderr) => {
            if (err) {
                console.log("执行失败:" + cmd + "\nError:" + err.message);
                resolve();
                return;
            }
            console.log("执行成功:" + cmd + "    耗时(" + (Date.now() - t) + ")毫秒");
            resolve(stdout);
        })
    });
}

export async function installCnpm() {
    let result = await systemExec('cnpm -v');
    if (!result) {
        console.log('install cnpm first, may be need 40s, please wait...');
        await systemExec('npm install cnpm -g --registry=https://registry.npm.taobao.org');
    }
}

/** 参数为：npm i xxx */
export async function npmExec(params: string) {
    let result = await systemExec('cnpm -v');
    if (!result) {
        console.log('install cnpm first, may be need 40s, please wait...');
        await systemExec('npm install cnpm -g --registry=https://registry.npm.taobao.org');
    }
    params = params.replace('npm i', 'cnpm i');
    return await systemExec(params);
}